import React from "react";
import { Breadcrumb, Icon, Tooltip, Popover, Select } from "antd";
import { Link, browserHistory } from "react-router";
import "styles/main.scss";
import menuRoute from "routes/menuRoute";
import { eventTrack, messages } from "share/common";
import configureStore from "stores";
import FeedbackIcon from "containers/components/feedback-icon";
import mainService from "containers/main.service";
import LogoImg from "images/logo.png";
import trial from "images/trail.png";
import SVGIcon from "components/SVGIcon";

let statistical = null;
//内部测试，试用中。展示信息。旧版
export function RenderTrialOrTestInfo() {
  const { tenant } = configureStore.store.getState().login;
  const { menuCollapse } = configureStore.store.getState().main;
  return (
    <div>
      {tenant.licenseType === "TRIAL" && (
        <Tooltip title={messages("basic-1.key77") /*试用中*/} placement="right">
          <div className="trial-info">
            <img src={trial} className={"trail-img-icon"} />
            {!menuCollapse && messages("basic-1.key77") /*试用中*/}
          </div>
        </Tooltip>
      )}
      {tenant.licenseType === "TEST" && (
        <Tooltip title={messages("basic-1.key78") /*内部测试*/} placement="right">
          <div className="trial-info">
            <img src={trial} className={"trail-img-icon"} />
            {!menuCollapse && messages("basic-1.key78") /*内部测试*/}
          </div>
        </Tooltip>
      )}
    </div>
  );
}

export function RenderCompanyName() {
  const { tenant, loginCompany } = configureStore.store.getState().login;
  const { menuCollapse } = configureStore.store.getState().main;
  return (
    <div className="menu-header-container" id="menu-header-container-guide-id">
      <div className="company-name text-ellipsis" onClick={goIndex}>
        <Popover content={loginCompany.name} placement="bottomLeft">
          <img src={tenant.logoURL || LogoImg} style={{ width: 20, height: 20 }} />
        </Popover>
        &nbsp;
        {!menuCollapse && (
          <Popover content={loginCompany.name} placement="bottomLeft">
            <span className="name">{!menuCollapse && loginCompany.name}</span>
          </Popover>
        )}
      </div>
    </div>
  );
}

export function goIndex() {
  const tempHome = sessionStorage.getItem("hly.tempHome");
  const { menuTree } = configureStore.store.getState().login;
  let url = menuTree.keyUrl.home || menuTree.keyUrl.dashboard;
  if (tempHome && tempHome === "home") {
    url = menuTree.keyUrl.home;
  } else if (tempHome && tempHome === "dashboard") {
    url = menuTree.keyUrl.dashboard;
  }
  if (!url) {
    /*超强大容错。找menuTree的前20个菜单，找到URL就停止。避免登录后前面菜单没有URL无法登录进去。
     容错强大容易漏掉bug，只要进去的不是第一个菜单，就说明有问题，开发者请注意排查。*/
    for (let i = 0; i < 20; i++) {
      url = getUrl(menuTree.menuTree[i]);
      if (url) break;
    }
  }
  function getUrl(menu) {
    return menu.subMenuTree && menu.subMenuTree.length ? getUrl(menu.subMenuTree[0]) : menu.url;
  }
  url && browserHistory.push(url);
}

export function RenderMenuBottomFunc(params) {
  const { tenant, menuTree, user } = configureStore.store.getState().login;
  const { menuCollapse } = configureStore.store.getState().main;
  const { onlineServiceUrl, that } = params;
  const noFeedBack = !menuTree.allAPIMenuItem["customer-feedback"];
  const noCustomer = !onlineServiceUrl || window.isBaiduAiCloud || !menuTree.allAPIMenuItem["contact-customer"];
  const collapsedIcon = (
    <Tooltip title={menuCollapse ? messages("basic-1.key75") /*展开*/ : messages("common.fold") /*收起*/}>
      <SVGIcon type={menuCollapse ? "unfold" : "fold"} />
    </Tooltip>
  );
  const customerIcon = (
    <Tooltip title={messages("basic-1.key76") /*在线客服*/}>
      <span onClick={() => goMenu("contact-customer", onlineServiceUrl)}>
        <SVGIcon type="customer-service" />
      </span>
    </Tooltip>
  );
  return (
    <div className="menu-footer-container">
      {menuCollapse ? (
        tenant.resourceLayout === "T" ? (
          <div
            className="menu-footer-unfold-new"
            onClick={() => {
              that.onCollapse(!menuCollapse);
            }}
          >
            {collapsedIcon}
          </div>
        ) : (
          <div className="menu-footer-unfold">
            {!noCustomer && <div className="vertical-icon-area">{customerIcon}</div>}
            {!noFeedBack && (
              <div className="vertical-icon-area">
                <Tooltip title={messages("basic-1.key81") /*截图反馈*/}>
                  <span onClick={() => that.feedbackRef.feedbackHandler()}>
                    <SVGIcon type="screen-shoot" />
                  </span>
                </Tooltip>
                <FeedbackIcon onRef={(feedbackRef) => (that.feedbackRef = feedbackRef)} />
              </div>
            )}
            <div
              className="vertical-icon-area"
              onClick={() => {
                that.onCollapse(!menuCollapse);
              }}
            >
              {collapsedIcon}
            </div>
          </div>
        )
      ) : (
        <div className="menu-footer-fold">
          <span
            className="icon-area"
            onClick={() => {
              that.onCollapse(!menuCollapse);
            }}
          >
            {collapsedIcon}
          </span>
          {!noFeedBack && (
            <span className="icon-area">
              <Tooltip title={messages("basic-1.key81") /*截图反馈*/}>
                <span onClick={that.feedbackRefHandler}>
                  <SVGIcon type="screen-shoot" />
                </span>
              </Tooltip>
              <FeedbackIcon onRef={(feedbackRef) => (that.feedbackRef = feedbackRef)} />
            </span>
          )}
          {!noCustomer && <span className="icon-area">{customerIcon}</span>}
        </div>
      )}
    </div>
  );
}

function goMenu(key, onlineServiceUrl) {
  const { company } = configureStore.store.getState().login;
  const { language } = configureStore.store.getState().main;
  const map = {
    zh_cn: "cooperate",
    en: "en_cooperate",
    ja: "ja_cooperate",
    zh_tw: "cooperate",
    it_IT: "en_cooperate",
  };
  if (key === "doc" && !company.helpDocumentStatus) {
    // window.open("https://help.huilianyi.com/web/#/3?page_id=29", "_blank");task 60911
    window.open(
      "https://www.yuque.com/docs/share/69c03bb0-7524-414d-b500-bb95347598f8?# 《环境搭建 Environment Setup》",
      "_blank"
    );
  } else if (key === "contact-us") {
    window.open(`https://www.huilianyi.com/${map[language.code] || "en_cooperate"}`, "_blank");
  } else if (key === "contact-customer") {
    window.open(onlineServiceUrl, "_blank");
  } else {
    browserHistory.push(menuRoute.getPageUrlByKey(key));
  }
}

export function RenderMessagesCenterSvg() {
  const { menuTree } = configureStore.store.getState().login;
  const message = menuTree.allAPIMenuItem["messages-center"];
  return message ? (
    <span onClick={() => goMenu("messages-center")}>
      <SVGIcon type="messages" className="svg-icon right-gap-20" />
    </span>
  ) : null;
}

export function RenderToolMenuListSvg(params) {
  const { menuTree, user } = configureStore.store.getState().login;
  const { toolMenuList, onlineServiceUrl } = params;
  const noCustomer =
    !onlineServiceUrl ||
    (user.language && user.language.toLowerCase() !== "zh_cn") ||
    window.isBaiduAiCloud ||
    !menuTree.allAPIMenuItem["contact-customer"];
  const helpContent = (
    <div>
      {toolMenuList && toolMenuList.length
        ? toolMenuList.map((item) => {
            return (
              (item.key === "contact-customer" ? !noCustomer : true) && (
                <div onClick={() => goMenu(item.key, onlineServiceUrl)} style={{ marginBottom: 8, cursor: "pointer" }}>
                  {item.resourceName}
                </div>
              )
            );
          })
        : null}
    </div>
  );
  return toolMenuList.length ? (
    <Popover trigger="hover" content={helpContent}>
      <span>
        <SVGIcon type="more-new" className="svg-icon right-gap-20" />
      </span>
    </Popover>
  ) : null;
}

export function renderBreadcrumb(error) {
  const { currentPage } = configureStore.store.getState().main;
  const breadcrumb = currentPage || [];
  return error ? null : (
    <Breadcrumb className="breadcrumb text-ellipsis" separator={<Icon type="right" />}>
      {breadcrumb.map((item, i) => {
        const classNameStr = i === breadcrumb.length - 1 ? "last-breadcrumb" : null;
        if (item.url && i !== breadcrumb.length - 1) {
          return item.key === "help-center-user" ? null : (
            <Breadcrumb.Item key={item.key} className="breadcrumb-item">
              <Link to={mainService.transRealUrl(item)} state={item.state}>
                {item.resourceName ? item.resourceName : messages(`menu.${item.key}`)}
              </Link>
            </Breadcrumb.Item>
          );
        }
        return (
          <Breadcrumb.Item key={item.key} className={classNameStr}>
            {item.resourceName ? item.resourceName : messages(`menu.${item.key}`)}
          </Breadcrumb.Item>
        );
      })}
    </Breadcrumb>
  );
}

export function checkHasMenuValue(item, menuValue) {
  const { language } = configureStore.store.getState().main;
  let bool = true;
  const hasPin = matchEnglish(menuValue);
  const hasHanZi = matchChinese(menuValue);
  const hasPinStr = (hasPin || []).join("").toLowerCase();
  const originNamePin = (item.pinyinResourceName || "").split("|");
  const resourceName = item.resourceName;
  if (["zh_cn", "zh_tw"].includes(language.code.toLowerCase())) {
    if (hasHanZi && !hasPin) {
      bool = hasHanZi.every((han) => resourceName.includes(han));
    } else if (!hasHanZi && hasPin) {
      bool = judgeIncludePin();
    } else if (hasHanZi && hasPin) {
      bool = hasHanZi.every((han) => resourceName.includes(han)) && judgeIncludePin();
    }
  } else {
    bool = resourceName.toLowerCase().includes(menuValue.toLowerCase());
  }
  return bool;

  function judgeIncludePin() {
    if (hasPinStr.length === 1 && !hasHanZi) {
      return originNamePin.some((ori) => ori && ori[0].toLowerCase() === hasPinStr);
    }
    let include = (item.pinyinResourceName || "").replace(/\|/g, "").toLowerCase().includes(hasPinStr);
    return matchEnglish(item.resourceName)
      ? include
      : include &&
          originNamePin.some((pin) =>
            hasPinStr.length >= pin.length
              ? hasPinStr.includes(pin)
              : pin.includes(hasPinStr) && hasPinStr.includes(pin[0])
          );
  }
}

export function matchMenuValue(item, menuValue) {
  const { language } = configureStore.store.getState().main;
  let fakeName = "";
  let dom = item.resourceName;
  const hasPin = matchEnglish(menuValue);
  const hasHanZi = matchChinese(menuValue);
  let hasPinStr = (hasPin || []).join("").toLowerCase();
  const originNamePin = (item.pinyinResourceName || "").split("|");
  const resourceName = item.resourceName;
  if (language.code.toLowerCase() === "zh_cn" || language.code.toLowerCase() === "zh_tw") {
    if (!hasHanZi && hasPin && item.highLightKey) {
      replaceDom(item.highLightKey);
      return <span dangerouslySetInnerHTML={{ __html: dom }} />;
    }
    if (hasHanZi && !hasPin) {
      replaceDom(hasHanZi);
    } else if (!hasHanZi && hasPin) {
      replacePin();
      if (!fakeName) return resourceName;
      replaceDom(fakeName);
    } else if (hasHanZi && hasPin) {
      hasHanZi.forEach((han) => {
        if (resourceName.includes(han) && !fakeName.includes(han)) {
          fakeName += han;
        }
      });
      if (fakeName.length < resourceName.length) {
        replacePin();
      }
      if (!fakeName) return resourceName;
      replaceDom(fakeName);
    }
    return <span dangerouslySetInnerHTML={{ __html: dom }} />;
  }
  return (
    <span
      dangerouslySetInnerHTML={{
        __html: item.resourceName.replace(new RegExp(`${menuValue}`, "i"), function (arg) {
          return `<span style='color: #4B8DFF'>${arg}</span>`;
        }),
      }}
    />
  );

  function replacePin() {
    if (hasPinStr && matchEnglish(resourceName)) {
      let ang = matchEnglish(resourceName).join("").toLowerCase();
      if (ang.includes(hasPinStr)) {
        fakeName += resourceName.match(new RegExp(`${hasPinStr}`, "i"))[0];
      } else if (hasPinStr.includes(ang)) {
        fakeName += resourceName.match(new RegExp(`${ang}`, "i"))[0];
        hasPinStr = hasPinStr.substring(ang.length);
      }
    }
    originNamePin.forEach((ori, index) => {
      if (!hasHanZi && hasPinStr.length === 1 && ori === hasPinStr) {
        fakeName += resourceName[index];
        hasPinStr = "";
        return;
      }
      const tag = hasPinStr ? (hasPinStr.length >= ori.length ? hasPinStr.indexOf(ori) : ori.indexOf(hasPinStr)) : -1;
      if (tag !== -1 && !fakeName.includes(resourceName[index])) {
        fakeName += resourceName[index];
        if (hasPinStr.length >= ori.length) {
          hasPinStr = hasPinStr.substring(0, tag) + hasPinStr.substring(tag + ori.length);
        } else {
          hasPinStr = "";
        }
      }
    });
  }
  function replaceDom(param) {
    let arr = [];
    if (typeof param === "string") {
      let eng = matchEnglish(param);
      if (eng) {
        arr = param.replace(/[a-zA-Z]/g, "").split("");
        arr.push(eng.join(""));
      } else {
        arr = param.split("");
      }
    } else {
      arr = param;
    }
    arr.forEach((fake) => {
      dom = dom.replace(new RegExp(`${fake}`, "i"), function (arg) {
        return `<span style='color: #4B8DFF'>${arg}</span>`;
      });
    });
  }
}

export function resizeWidth() {
  setTimeout(() => {
    const width = configureStore.store.getState().main.menuWidth;
    const dom = document.querySelector(".slide-frame.animated");
    if (dom) {
      dom.style.width = `calc(100vw - ${width}px)`;
      dom.style.transition = "0.5s";
      dom.className = dom.className.replace(/full-width-([\d]+)/, `full-width-${width}`);
    }
  });
}

export function setScrollTop(hoverKey) {
  const resultMenu = document.getElementById("search-result-menu");
  const resultMenuH = resultMenu.offsetHeight;
  const nowMenuH = document.getElementById(hoverKey).offsetParent.offsetTop;
  if (nowMenuH > resultMenuH - 50) {
    resultMenu.scrollTop = nowMenuH - resultMenuH + 150;
  } else {
    resultMenu.scrollTop = 0;
  }
}
export function onKeyDown(e, _this) {
  const { resultMenu, hoverKey, hoverKeyParent, menuValue } = _this.state;
  const that = _this;
  const { language } = _this.props;
  const keyCode = e.keyCode || e.which || e.charCode;
  let flag = 0;
  const len = resultMenu.length;
  if (keyCode === 38) {
    e.preventDefault();
  }
  const hasPin = matchEnglish(menuValue);
  const hasHanZi = matchChinese(menuValue);
  const currentLan = language.code.toLowerCase() === "zh_cn" || language.code.toLowerCase() === "zh_tw";
  if (!menuValue || !menuValue.replace(/\s/g, "") || (currentLan && !hasPin && !hasHanZi)) {
    return;
  }
  if (!len) {
    return;
  }
  if (hoverKey && keyCode === 13) {
    browserHistory.push(menuRoute.getPageUrlByKey(hoverKey));
    return;
  }
  if (
    keyCode === 38 &&
    (hoverKey === resultMenu[0].functionCode ||
      (resultMenu[0].subMenuTree.length && hoverKey === resultMenu[0].subMenuTree[0].functionCode))
  ) {
    return;
  }
  if (keyCode === 38 || keyCode === 40) {
    //上38,下40
    if (!hoverKey) {
      setHoverKey(0);
    } else {
      const lastMenu = resultMenu[len - 1];
      let lastKey = lastMenu.functionCode;
      if (lastMenu.subMenuTree && lastMenu.subMenuTree.length) {
        const childLen = lastMenu.subMenuTree.length;
        lastKey = lastMenu.subMenuTree[childLen - 1].functionCode;
      }
      if (lastKey === hoverKey && keyCode === 40) {
        setHoverKey(0);
        return;
      }
      const bool = resultMenu.some((item) => item.functionCode === hoverKey);
      if (!bool) {
        if (hoverKeyParent) {
          hasHoverKeyParent();
          return;
        }
        setHoverKey(0);
        return;
      }
      resultMenu.forEach((item, index) => {
        if (item.key === hoverKey) {
          flag =
            index > 0 ? (keyCode === 38 ? index - 1 : index === len - 1 ? len - 1 : index + 1) : keyCode === 38 ? 0 : 1;
          setHoverKey(flag);
        }
      });
    }
  }

  function hasHoverKeyParent() {
    let parentIndex = 0;
    for (let k = 0; k < len; k++) {
      if (resultMenu[k].functionCode === hoverKeyParent) {
        parentIndex = k;
        break;
      }
    }
    const arr = resultMenu[parentIndex].subMenuTree;
    let arrIndex = 0;
    const arrLen = arr.length;
    if (arr[arrLen - 1].functionCode === hoverKey && keyCode === 40) {
      setHoverKey(parentIndex + 1);
      return;
    }
    if (arr[0].functionCode === hoverKey && keyCode === 38) {
      setHoverKey(parentIndex - 1 < 0 ? 0 : parentIndex - 1, "last");
      return;
    }
    for (let m = 0; m < arrLen; m++) {
      if (arr[m].key === hoverKey) {
        arrIndex = m > 0 ? (keyCode === 38 ? m - 1 : m === arrLen - 1 ? arrLen - 1 : m + 1) : keyCode === 38 ? 0 : 1;
        const tempCode = arr[arrIndex].functionCode;
        that.setState(
          {
            hoverKey: tempCode,
          },
          () => {
            setScrollTop(that.state.hoverKey);
          }
        );
        break;
      }
    }
  }

  function setHoverKey(num, special) {
    const menuItem = resultMenu[num];
    let parent = "";
    let code = menuItem.functionCode;
    const openKeys = that.state.openKeys;
    if (menuItem.subMenuTree && menuItem.subMenuTree.length) {
      code = menuItem.subMenuTree[special === "last" ? menuItem.subMenuTree.length - 1 : 0].functionCode;
      parent = menuItem.functionCode;
      openKeys.push(parent);
    }
    that.setState(
      {
        openKeys,
        hoverKeyParent: parent,
        hoverKey: code,
      },
      () => {
        setScrollTop(that.state.hoverKey);
      }
    );
  }
}
export function inputChange(e, _this) {
  const { menuTree, language, tenant } = _this.props;
  const value = e.target.value;
  const hasPin = matchEnglish(value);
  const hasHanZi = matchChinese(value);
  const val = value.replace(/[^a-zA-Z]/g, function (arg) {
    return arg.match(/[^\u4e00-\u9fa5]/g) ? "" : arg;
  });
  const currentLan = language.code.toLowerCase() === "zh_cn" || language.code.toLowerCase() === "zh_tw";
  _this.setState({
    isSearchingMenu: !!val,
    menuValue: value,
  });
  if (!value || !value.replace(/\s/g, "") || (currentLan && !hasPin && !hasHanZi)) {
    _this.setState({
      resultMenu: [],
      hoverKey: "",
      isSearchingMenu: false,
      menuChanged: true,
    });
    return;
  }
  if (value && value.replace(/\s/g, "")) {
    delayStatistical(value, tenant);
  }
  if (currentLan) {
    if (val) {
      onMenuSearchChange(val, _this);
    }
  } else {
    onMenuSearchChange(value, _this);
  }
}

export function delayStatistical(value, tenant) {
  if (statistical) {
    clearTimeout(statistical);
  }
  statistical = setTimeout(function () {
    let cloud = {
      "console.huilianyi.com": "ALY",
      "console-my.huilianyi.com": "MLALY",
      "console-yp.huilianyi.com": "ALY",
      "console-yeepay.huilianyi.com": "ALY",
      "console-tc.huilianyi.com": "TXY",
      "watsons.huilianyi.com": "QCS",
      "console-hw.huilianyi.com": "HWY",
      "console-bd.huilianyi.com": "BDY",
      "console-dd.huilianyi.com": "DDY",
      "console-byd.huilianyi.com": "BYD",
      "console-welink.huilianyi.com": "WLKY",
      "console-seazen.huilianyi.com": "SZ",
    };
    eventTrack({
      category: "菜单栏搜索",
      action: `搜索内容：${value}`,
      label: {
        date: new Date().format("YYYY-MM-DD HH:mm:ss"),
        cloud: cloud[window.hostname],
        tenantName: tenant.tenantName,
      },
    });
  }, 1000);
}

export function onMenuSearchChange(value, _this) {
  const { menuTree, language } = _this.props;
  const subMenu = [],
    menu = [],
    hasPin = matchEnglish(value),
    hasHanZi = matchChinese(value);
  let result = [];
  const currentLan = language.code.toLowerCase() === "zh_cn" || language.code.toLowerCase() === "zh_tw";
  if (!value || !value.replace(/\s/g, "") || (currentLan && !hasPin && !hasHanZi)) {
    return;
  }
  menuTree.menuTree
    .filter((item) => {
      return item.key !== "toolbar" && item.key !== "common-functions" && item.resourceType !== "C";
    })
    .forEach((item) => {
      loopMenuTree(item);
    });

  function loopMenuTree(item) {
    if (item.subMenuTree && item.subMenuTree.length) {
      item.subMenuTree.forEach((sub) => {
        if (checkHasMenuValue(sub, value) || (sub.resourceType === "F" && checkTabMatchValue(sub, value))) {
          if (sub.subMenuTree && sub.subMenuTree.length) {
            if (hasHanZi) {
              if (excludeMenu(sub)) {
                subMenu.push(sub);
              }
            } else {
              sub.subMenuTree.forEach((deep) => {
                if (excludeMenu(deep) && (checkHasMenuValue(deep, value) || checkTabMatchValue(deep, value))) {
                  menu.push(deep);
                }
              });
            }
          } else {
            excludeMenu(sub) && menu.push(sub);
          }
        } else {
          loopMenuTree(sub);
        }
      });
    }
  }
  result = menu.concat(subMenu);
  _this.setState({
    resultMenu: result,
  });
}

function excludeMenu(menu) {
  return menu.resourceType !== "C" && !["home", "unbox-setting"].includes(menu.key);
}

export function checkTabMatchValue(item, value) {
  if (item.subMenuTree && item.subMenuTree.length) {
    return !!item.subMenuTree.find((sub) => checkTabMatchValue(sub, value));
  } else {
    if (item.subFunctions && item.subFunctions.length) {
      return !!item.subFunctions.find((sub) => checkHasMenuValue(sub, value));
    } else {
      return false;
    }
  }
}

export function clearMenuSearch(_this) {
  const { currentMenuPermission } = _this.props;
  const activeMenu = currentMenuPermission.currentMenu;
  let openKeys = [];
  if (activeMenu.resourceType !== "C" && activeMenu.parent && activeMenu.parent.length) {
    activeMenu.parent.forEach((item) => {
      openKeys.push(item.key);
    });
  }
  openKeys = openKeys.concat([activeMenu.key]);
  _this.setState({
    isSearchingMenu: false,
    resultMenu: [],
    menuValue: "",
    hoverKey: "",
    openKeys,
  });
}

export function matchEnglish(text) {
  return text.match(/[a-zA-Z]/g);
}

export function matchChinese(text) {
  return text.match(/[\u4e00-\u9fa5]/g);
}

export function renderSelectedKeys(selectedKeys, selectedKeysProps) {
  if (selectedKeys && selectedKeys.length) {
    if (selectedKeysProps && selectedKeysProps.length) {
      if (selectedKeysProps[0] !== selectedKeys[0]) {
        return selectedKeysProps;
      }
    }
    return selectedKeys;
  }
  return selectedKeysProps;
}
